﻿using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using Combination.Core;

namespace Combination.UI
{
    public class BasePage : Page
    {
        #region Private Member

        private object _viewModel;

        #endregion

        #region Public Properties

        public PageAnimation PageLoadAnimation { get; set; } = PageAnimation.SlideAndFadeInFromRight;

        public PageAnimation PageUnloadAnimation { get; set; } = PageAnimation.SlideAndFadeOutToLeft;

        public float SlideSeconds { get; set; } = 0.4f;

        public object ViewModelObject
        {
            get => _viewModel;
            set
            {
                if (_viewModel == value)
                    return;

                _viewModel = value;
                OnViewModelChanged();
                DataContext = _viewModel;
            }
        }

        #endregion

        public BasePage()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;

            if (PageLoadAnimation != PageAnimation.None)
                Visibility = Visibility.Collapsed;

            Loaded += BasePage_LoadedAsync;
            Unloaded += BasePage_UnloadedAsync;
        }

        private async void BasePage_UnloadedAsync(object sender, RoutedEventArgs e)
        {
            await AnimationOutAsync();
            (this.DataContext as PageVm)?.OnSourceUnloaded(this);
        }

        private async void BasePage_LoadedAsync(object sender, RoutedEventArgs e)
        {
            await AnimationInAsync();
            (this.DataContext as PageVm)?.OnSourceLoaded(this);
        }

        public async Task AnimationInAsync()
        {
            if (PageLoadAnimation == PageAnimation.None)
                return;

            switch (PageLoadAnimation)
            {
                case PageAnimation.SlideAndFadeInFromRight:
                    await this.SlideAndFadeInAsync(AnimationSlideInDirection.Right, SlideSeconds, size: (int)Application.Current.MainWindow.Width);
                    break;
            }
        }

        public async Task AnimationOutAsync()
        {
            if (this.PageLoadAnimation == PageAnimation.None)
                return;

            switch (this.PageUnloadAnimation)
            {
                case PageAnimation.SlideAndFadeOutToLeft:
                    await this.SlideAndFadeOutAsync(AnimationSlideInDirection.Left, SlideSeconds);
                    break;
            }
        }
        protected virtual void OnViewModelChanged() { }
    }
}
